import struct
import requests


# 在这里填写你的CurseForge API密钥
API_KEY = "$2a$10$yDlx/bENVUINAfrIe8hjI.Oma2HrCzU.DuXFB146ck3nnhh94n/Le"

# CurseForge API相关配置
API_URL = "https://api.curseforge.com/v1"


def curseforge_hash(file_path):
    """
    计算文件的 CurseForge 哈希值（修正版）
    与 VB 代码完全一致的实现
    """
    # 读取文件数据
    with open(file_path, 'rb') as f:
        data = f.read()
    
    # 过滤特殊字节：9(TAB), 10(LF), 13(CR), 32(SPACE)
    filtered_data = bytearray()
    for b in data:
        if b not in [9, 10, 13, 32]:
            filtered_data.append(b)
    
    length = len(filtered_data)
    h = 1 ^ length  # 修正：使用种子1（与VB一致）
    
    # 处理4字节块
    i = 0
    while i < length - 3:
        # 小端序读取4字节
        k = struct.unpack('<I', filtered_data[i:i+4])[0]
        
        # MurmurHash2 核心操作
        k = (k * 0x5BD1E995) & 0xFFFFFFFF
        k ^= k >> 24
        k = (k * 0x5BD1E995) & 0xFFFFFFFF
        
        h = (h * 0x5BD1E995) & 0xFFFFFFFF
        h ^= k
        
        i += 4
    
    # 处理剩余字节
    remaining = length - i
    if remaining == 3:
        h ^= filtered_data[i] | (filtered_data[i+1] << 8) | (filtered_data[i+2] << 16)
        h = (h * 0x5BD1E995) & 0xFFFFFFFF
    elif remaining == 2:
        h ^= filtered_data[i] | (filtered_data[i+1] << 8)
        h = (h * 0x5BD1E995) & 0xFFFFFFFF
    elif remaining == 1:
        h ^= filtered_data[i]
        h = (h * 0x5BD1E995) & 0xFFFFFFFF
    
    # 最终混合
    h ^= h >> 13
    h = (h * 0x5BD1E995) & 0xFFFFFFFF
    h ^= h >> 15
    
    return h


def get_curseforge_modId(hashes, headers):
    """
    Query CurseForge API to get mod information based on file fingerprints.
    """
    url = f"{API_URL}/fingerprints/432"
    data = {
        "fingerprints": hashes
    }
    
    try:
        response = requests.post(url, headers=headers, json=data)
        response.raise_for_status()
        result = response.json()
        exactMatches = result["data"]["exactMatches"]
        if len(exactMatches) == 0:
            return None
        # print(exactMatches[0]["file"]["modId"])
        
        return exactMatches[0]["file"]["modId"]
    except requests.exceptions.RequestException as e:
        print(f"网络请求错误: {e}")
        return None


def get_curseforge_mod_info(modId,headers):
    """
    Search for mods on CurseForge using various filters.
    """

    
    try:
        response = requests.get(f'{API_URL}/mods/{modId}', headers = headers)
        result = response.json()
        return result["data"]["slug"]
    except requests.exceptions.RequestException as e:
        print(f"网络请求错误: {e}")
        return None


def get_mod_slug(file_path):

    
    headers = {
        "Accept": "application/json",
        "x-api-key": API_KEY
    }
    
    hash_value = curseforge_hash(file_path)
    # 查询CurseForge获取Mod信息
    modId = get_curseforge_modId([hash_value], headers)
    if modId:
        return get_curseforge_mod_info(modId,headers)
    else:
        # print("\n未在CurseForge上找到匹配的Mod")
        return None
            